// pages/vote/vote.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _openid:'',//当前投票的发起人openid
    voteID: '', //当前投票的id
    avatarUrl: '', //发起人头像
    nickName: '', //发起人昵称
    imgList: [], //图片临时缓存数组
    multiIndex: [0, 0], //当前投票的投票方式
    voteTitle: '', //当前投票的标题
    voteDesc: '', //当前投票的补充描述
    optionList: [], //当前投票的选项列表
    endDate: '', //当前投票的截止日期
    isAnonymous: false, //当前投票是否匿名
    isPublicity: false, //当前投票是否可分享
    isExpired: false, //当前投票是否过期
    isSelf: false, //当前投票是否为本人发起
    pickedOption: [], //当前用户选择的选项
    voteStatus: { //投票状态
      alreadyVoted: false,
      totalVoteCount: 0,
      optionStatus: []
    }
  },
  /**
   * 当前用户选择的选项双向传输
   */
  onPickOption(e) {
    if (this.data.multiIndex[1] > 0) {
      this.setData({
        pickedOption: e.detail.value
      })
    } else {
      this.setData({
        pickedOption: [e.detail.value]
      })
    }
  },
  /**
   * 投票并返回状态
   */
  onTapVote() {
    const msg = this.checkVoteValid()
    if (msg) { // 在if判断时，null会被转换为false
      wx.showToast({ // 调用提示框API显示提示内容
        title: msg, // 提示框中的文字内容
        icon: 'none' // 提示框的图标，none表示没有图标
      })
      return // 提前返回，函数会在这里结束，后面的内容不会执行
    }
    if (this.data.isAnonymous) {
      const postData = {
        voteID: this.data.voteID,
        pickedOption: this.data.pickedOption
      }
      //将postData数据上传到服务端
      wx.cloud.callFunction({
        name: 'vote',
        data: {
          postData
        }
      }).then(res => {
        console.log(res)
        this.getVoteStatusFromServer(this.data.voteID) // 从服务端获取投票情况
      }).catch(res => {
        console.error(res)
        wx.showToast({
          title: '投票失败',
          icon: 'none'
        })
      })
    } else {
      const _this = this // 在API接口中的函数中，this会被改变，因此需要提前获取this的值到_this中
      console.log(_this.data.pickedOption)
      wx.getUserInfo({
        success(res) { // 授权成功后，调用wx.getUserInfo接口时会回调这个函数
          const postData = { // 需要提交的数据
            voteID: _this.data.voteID,
            userInfo: res.userInfo, // 获取用户信息
            pickedOption: _this.data.pickedOption
          }
          console.log(postData.pickedOption)
          wx.cloud.callFunction({
            name: 'vote',
            data: {
              postData
            }
          }).then(res => {
            console.log(res)
            _this.getVoteStatusFromServer(_this.data.voteID) // 从服务端获取投票情况
          }).catch(res => {
            console.error(res)
            wx.showToast({
              title: '投票失败',
              icon: 'none'
            })
          })
        }
      })
    }
  },

  checkVoteValid() {
    const length = this.data.multiIndex[1] + 1
    const pickedOptionLength = this.data.pickedOption.length
    console.log(length)
    console.log(this.data.pickedOption)
    if (length < pickedOptionLength) {
      return '超过' + length + '选'
    } else if (length > pickedOptionLength) {
      return '不足' + length + '选'
    } else {
      return null
    }
  },

  getVoteDataFromServer(voteID) {
    //wx.hideShareMenu({})
    var that = this
    if (voteID === 'test') {
      /*以下是伪造的数据 */
      const voteData = {
        _openid:'oXCIO5OsV3fsnmjxs7EYdrlkXL5A',
        avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/ohDdvzhycYXS6oWhYK9SMP0DYkfa3ou5ntCgHKRibUaoAabn69yd1QxfEx6zv50A4DwXR7nuJJxibkIeFwG93kBQ/132',
        nickName: 'shiftlessCat',
        multiIndex: [0, 0],
        voteTitle: '测试数据投票标题',
        voteDesc: '测试数据投票描述',
        imgList: ['cloud://vote-6giwa1pvdf7402cb.766f-vote-6giwa1pvdf7402cb-1301129581/textVoteImg/1614503330300.jpg'],
        optionList: [
          '测试数据选项1',
          '测试数据选项2',
          '测试数据选项3',
          '测试数据选项4'
        ],
        endDate: '2021-03-01',
        isAnonymous: false,
        isPublicity: true,
      }
      /*以上是伪造的数据 */
      wx.showLoading({
        title: '加载中',
      })
      const isExpired = this.checkExpired(voteData.endDate)
      var imgList = this.downloadImg(voteData.imgList)
      //console.log('imgList:', this.data.imgList)
      setTimeout(function () {
        that.setData({
          voteID,
          _openid:voteData._openid,
          avatarUrl: voteData.avatarUrl,
          nickName: voteData.nickName,
          multiIndex: voteData.multiIndex,
          voteTitle: voteData.voteTitle,
          imgList: imgList,
          voteDesc: voteData.voteDesc,
          optionList: voteData.optionList,
          endDate: voteData.endDate,
          isAnonymous: voteData.isAnonymous,
          isPublicity: voteData.isPublicity,
          isExpired,
          isSelf,
        })
        //console.log('imgList:', that.data.imgList)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '读取信息成功',
              icon: 'success',
              duration: 1000
            })
          },
        })
      }, 1000)
    } else {
      //从服务端获取投票信息
      wx.showLoading({
        title: '加载中',
      })
      const db = wx.cloud.database()
      db.collection('votes').doc(voteID).get()
        .then(res => {
          const voteData = res.data
          const isExpired = this.checkExpired(voteData.endDate)
          const isSelf = that.checkSelf(voteData._openid)
          console.log('isSelf:',this.data.isPublicity)
          var imgList = this.downloadImg(voteData.imgList)
          setTimeout(function () {
            that.setData({
              voteID,
              avatarUrl: voteData.avatarUrl,
              nickName: voteData.nickName,
              multiIndex: voteData.multiIndex,
              voteTitle: voteData.voteTitle,
              voteDesc: voteData.voteDesc,
              imgList: imgList,
              optionList: voteData.optionList,
              endDate: voteData.endDate,
              isAnonymous: voteData.isAnonymous,
              isPublicity: voteData.isPublicity,
              isExpired,
              isSelf,
            })
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '读取信息成功',
                  icon: 'success',
                  duration: 1000
                })
              },
            })
          }, 1000)
        })
        .catch(res => {
          console.error(res)
          wx.showToast({
            title: '获取投票失败',
            icon: 'none'
          })
        })
    }
  },

  getVoteStatusFromServer(voteID) {
    if(this.data._openid === 'oXCIO5OsV3fsnmjxs7EYdrlkXL5A'){
      wx.showShareMenu({})
    }
    if (voteID === 'test') {
      /*以下是伪造的数据 */
      const voteStatus = {
        alreadyVoted: true,
        totalVoteCount: 100,
        optionStatus: [{
          count: 25,
          vote: false
        }, {
          count: 35,
          vote: true
        }, {
          count: 10,
          vote: false
        }, {
          count: 30,
          vote: false
        }]
      }
      /*以上是伪造的数据 */
      this.setData({
        voteStatus
      })
    } else {
      //从服务端获取投票情况
      wx.cloud.callFunction({ // 使用小程序端API调用云函数
        name: 'getVoteStatus', // 指定调用的云函数名
        data: {
          voteID // 将投票ID传到服务端
        }
      }).then(res => {
        console.log('控制台输出服务端返回的结果:', res) // 控制台输出服务端返回的结果
        this.setData({ // 将获取的投票情况更新到data对象中
          voteStatus: res.result
        })
      }).catch(err => {
        console.error('调用云函数错误', err) // 如果出现异常，控制台输出异常详情
        wx.showToast({ // 调用提示框API提示用户获取数据失败
          title: '获取投票数据失败',
          icon: 'none'
        })
      })
    }
  },
  checkExpired(endDate) {
    const now = new Date()
    const nowYear = now.getFullYear()
    const nowMonth = now.getMonth() + 1
    const nowDay = now.getDate()
    const endDateArray = endDate.split('-')
    const endYear = Number(endDateArray[0])
    const endMonth = Number(endDateArray[1])
    const endDay = Number(endDateArray[2])

    if (nowYear > endYear) {
      return true
    }
    if ((nowYear === endYear) && (nowMonth > endMonth)) {
      return true
    }
    if ((nowYear === endYear) && (nowMonth === endMonth) && (nowDay > endDay)) {
      return true
    }
    return false
  },
  checkSelf(_openid){
    wx.cloud.callFunction({
      name:'useInfo',
      complete:res=>{
        //console.log('checkSelf:',res.result.openid)
        //console.log('_openid:',_openid)
        if(res.result.openid === _openid){
          this.setData({
            isSelf:true
          })
        }else{
          this.setData({
            isSelf:false
          })
        }
      }
    })
  },

  downloadImg(photoTempPath) {
    var imgDownloadList = new Array
    wx.cloud.getTempFileURL({
        fileList: photoTempPath,
      }).then(res => {
        for (let i = 0; i < res.fileList.length; i++) {
          imgDownloadList[i] = res.fileList[i].tempFileURL
        }
      })
      .catch(err => {
        console.log('获取图像失败', err)
      })
    return imgDownloadList
  },
  /**
   * 预览图片
   */
  previewImg(e) {
      wx.previewImage({
        urls: this.data.imgList,
        current: this.data.imgList[e.currentTarget.dataset.id]
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    const voteID = options.voteID
    this.getVoteDataFromServer(voteID)
    this.getVoteStatusFromServer(voteID)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '邀请您参与投票',
      path: '/pages/vote/textVote?voteID=' + this.data.voteID
    }
  },
})